package org.imagic.module.think;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;

/**
 * User: Ruijie Date: 2016/11/22
 * 创建java对象的五种方式
 */
public class ObjectCreation {

    public static void main(String[] args) throws Exception{
        //By using new keyword
        Employee emp1=new Employee();
        emp1.setName("Naresh");
        System.out.println(emp1+",hashcode:"+emp1.hashCode());
        //By using Class class's newInstance() method
        Employee emp2=(Employee)Class.forName("org.imagic.module.think.Employee").newInstance();
        emp2.setName("Rishi");
        //Employee emp3=Employee.class.newInstance();
        System.out.println(emp2+", hashCode:"+emp2.hashCode());
        Constructor<Employee> constructor=Employee.class.getConstructor();
        Employee emp3=constructor.newInstance();
        emp3.setName("Yogesh");
        System.out.println(emp3+",hashCode:"+emp3.hashCode());
        //By using clone() method
        Employee emp4= (Employee) emp3.clone();
        emp4.setName("Atul");
        System.out.println(emp4+",hashCode:"+emp4.hashCode());
        //By using Deserialization
        //serialization
        ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("data.obj"));
        out.writeObject(emp4);
        out.close();
        ObjectInputStream in=new ObjectInputStream(new FileInputStream("data.obj"));
        Employee emp5= (Employee) in.readObject();
        in.close();
        emp5.setName("Akash");
        System.out.println(emp5+",hashCode:"+emp5.hashCode());
    }
}
class Employee implements Cloneable,Serializable{
    private static final long serialVersionUID=1L;
    private String name;
    public Employee(){
        System.out.println("Employee Constructor Called");
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }

    @Override
    public String toString() {
        return "Employee[name="+name+"]";
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object obj=null;
        obj=super.clone();
        return obj;
    }

    @Override
    public boolean equals(Object obj) {
        if(this==obj)
            return true;
        if(obj==null)
            return false;
        if(getClass()!=obj.getClass())
            return false;
        Employee other= (Employee) obj;
        if(name==null){
            if(other.name!=null)
                return false;
        }else if(!name.equals(other.name))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime=31;
        int result=1;
        result=prime*result+(name==null?0:name.hashCode());
        return result;
    }
}
